import { BASE_URL } from '@/config'
 
interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: Record<string, string>
}
 
const request = async <T = any>(options: RequestOptions): Promise<{ code: string; data?: T; msg?: string }> => {
  const { url, method = 'GET', data, header = {} } = options
  
  try {
    const res = await uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
		'Authorization': uni.getStorageSync("token"),
        ...header
      }
    })
    
    console.log('res.data',res.data)
	console.log('res.statusCode',res.statusCode)
    //const response = res as { code: number; data?: T; message?: string }
    if(res.statusCode === 401 ){
		uni.redirectTo({
			url:'/pages/login/login'
		})
	}
	else if (res.statusCode === 500) {
		uni.showToast({ title: res.data.msg, icon: 'none' });
	}
    return res.data
  } catch (error) {
    console.error('请求出错:', error)
    throw error
  }
}
 
export default request